package com.phpxiu.app.view;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.phpxiu.app.adapter.MyBlackListAdapter;
import com.phpxiu.app.adapter.holder.MyBlackViewHolder;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.list.BlackUser;
import com.phpxiu.app.model.response.BlackListModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.ListEmptyView;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.dialog.BlackListOperaMenus;
import com.tencent.TIMFriendResult;
import com.tencent.TIMFriendshipManager;
import com.tencent.TIMValueCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * 设置--黑名单列表
 * Created by 吴金洲 on 2016/8/3
 */
public class MyBlackList extends UIBase implements View.OnClickListener,
        AdapterView.OnItemLongClickListener,
        PullToRefreshView.OnRefreshListener2<ListView>,BlackListOperaMenus.BlackListOperaCallBack {
    public final static String TAG="MyBlackList";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private List<BlackUser> blacks=new ArrayList<BlackUser>();
    private PullToRefreshListView ptrRefreshView;
    private ListView mListView;
    private ListEmptyView emptyView;
    private MyBlackListAdapter mAdapter;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private List<String>ids=new ArrayList<String>();
    private BlackListOperaMenus operaMenus;
    private WindowLayout mainView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_black_list);
        mainView=(WindowLayout)findViewById(R.id.root_view);
        init();
    }

    /**
     * 初始化界面
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        ptrRefreshView=(PullToRefreshListView)findViewById(R.id.my_black_pull_refresh_list);
        mListView=ptrRefreshView.getRefreshableView();
        emptyView=new ListEmptyView(this);
        emptyView.setMsg(getString(R.string.list_empty_title));
        mListView.setOnItemLongClickListener(this);
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new MyBlackListAdapter(this,blacks);
        mListView.setAdapter(mAdapter);
        operaMenus=new BlackListOperaMenus(this);
        operaMenus.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
        operaMenus.setOperaCallBack(this);
        request(mOpera);
    }

    /**
     * 初始化请求
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder(false);
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_GET_BLOCK_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(BlackListModel.class) {
            @Override
            public void onSuccess(Object model) {
                BlackListModel m = (BlackListModel) model;
                emptyView.loaded();
                KKYUtil.log("黑名单列表数据：" + m.getResponseStr());
                try {
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        blacks.clear();
                        pageIndex = 1;
                    } else {
                        if (currentAllRecords > 0 && blacks.size() > 0 && blacks.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    blacks.addAll(m.getData().getUserlist());
                    mAdapter.notifyDataSetChanged();
                    mainView.showTopMsg(getString(R.string.long_click_delete));
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                listEmpty(blacks.size() == 0);
            }

            @Override
            public void onErr(String errMsg) {
                listEmpty(blacks.size() == 0);
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof MyBlackViewHolder){
            MyBlackViewHolder holder=(MyBlackViewHolder)view.getTag();
            KKYUtil.log(TAG, "操作：" + holder.getUid());
            operaMenus.show(holder.getUid(),holder.getPosition());
        }
        return true;
    }

    @Override
    public void onCancelBlackList(String uid, int position) {
        delBlackList(uid);
        blacks.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 删除黑名单
     * @param uid
     */
    private void delBlackList(final String uid){
        ids.clear();
        ids.add(uid);
        TIMFriendshipManager.getInstance().delBlackList(ids,new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess(List<TIMFriendResult> timFriendResults) {
                for(BlackUser user:blacks){
                    if(uid.equals(user.getUid())){
                        blacks.remove(user);
                        break;
                    }
                }
                mAdapter.notifyDataSetChanged();
                notifySever(uid);
            }
        });
    }

    /**
     * 同步服务器黑名单数据
     */
    private void notifySever(String uid){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid",uid);
        OKHttp.post(HttpConfig.API_ADD_CANCEL_BLOCK_BY_UID,param.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {

            }

            @Override
            public void onErr(String errMsg) {

            }
        });
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(blacks.size()!=0&&blacks.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptrRefreshView != null) {
            if(isEmpty) {
                ptrRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptrRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }
}
